﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using MyApp.Infrastructure.Messages;
using MVVMFramework.Messaging;
using Microsoft.Practices.Composite.Presentation.Events;
using MVVMFramework.Core.ViewModel;
using Microsoft.Practices.ServiceLocation;
using MVVMFramework.Core.View;

namespace MyApp.Infrastructure.Listeners
{
    public class SearchTaskListener
    {
        public SearchTaskListener()
        {
            Messenger.Get<SearchTaskMessage>().Subscribe(this.HandleSearchTaskMessage, ThreadOption.UIThread, true, this.CanHandleSearchTaskMessage);
        }

        private bool CanHandleSearchTaskMessage(SearchTaskMessageArgs args)
        {
            return true;
        }

        private void HandleSearchTaskMessage(SearchTaskMessageArgs args)
        {
            //fetch a IListVM<T> instance
            var viewModelType = typeof(IListVM<>).MakeGenericType(args.EntityType);
            var viewModelInstance = ServiceLocator.Current.GetInstance(viewModelType) as IListVM;

            //initialize the viewmodel
            viewModelInstance.Initialize(args);

            //fetch a IListView<T> instance
            var viewType = typeof(IListView<>).MakeGenericType(args.EntityType);
            var viewInstance = ServiceLocator.Current.GetInstance(viewType) as IView;

            //marry view and viewmodel
            viewInstance.ViewModel = viewModelInstance;

            //publish the view
            Messenger.Get<CreateViewMessage>().Publish(new CreateViewMessageArgs
            {
                Position = ViewPosition.Center,
                Title = args.EntityType.Name, //there could be some xml configuration where EntityTypes are associated to strings
                View = new Lazy<object>(() => viewInstance)
            });
        }
    }
}
